package com.boot2.core.aop;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
* @author zhangweilin
* @date 2020/12/16 22:06
* @Description:
*/ 
@Component
@CommonsLog
public class InjectBeanSelfProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//		System.out.println("bean.getClass().getName()1: "+bean.getClass().getName());

		//有时可能在本方法中获取到的是原实例，要在postProcessAfterInitialization方法中获取到的才是代理实例
		if (bean instanceof BeanSelfAware) {
			BeanSelfAware self = (BeanSelfAware) bean;
			self.setSelf(bean);
			log.info("注入BeanSelfAware,bean: "+bean.getClass().getName() );
//			System.out.println("+++++++++++++++++++++++++++++++++++++++++");

			return self;
		}

		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//		System.out.println("bean.getClass().getName()2: "+bean.getClass().getName());
		//有时可能在本方法中获取到的是原实例，要在postProcessAfterInitialization方法中获取到的才是代理实例
		if (bean instanceof BeanSelfAware) {
			BeanSelfAware self = (BeanSelfAware) bean;
			self.setSelf(bean);
			log.info("注入BeanSelfAware,bean: "+bean.getClass().getName() );
//			System.out.println("+++++++++++++++++++++++++++++++++++++++++");

			return self;
		}
		return bean;
	}

}
